package com.jrtc.base.util;

import java.util.Calendar;

public class AgeUtil {
    /**
     * 根据身出生日期获取年龄
     *
     * @param birthday 出生日期
     *
     * @return 年龄
     */
    public static int getAgeByBirthday(String birthday) {
        try {
            Calendar currentDate = Calendar.getInstance();

            int bornYear = Integer.valueOf(birthday.substring(0, 4));
            int bornMonth = Integer.valueOf(birthday.substring(5, 7));
            int bornDay = Integer.valueOf(birthday.substring(8));

            int currentYear = currentDate.get(Calendar.YEAR);
            int currentMonth = currentDate.get(Calendar.MONTH) + 1;
            int currentDay = currentDate.get(Calendar.DATE);

            int age = currentYear - bornYear;
            if (bornMonth  > currentMonth ||
                    (bornMonth == currentMonth && bornDay > currentDay)) {
                age--;
            }
            if (age < 1){
                age = 1;
            }
            return age;
        } catch (Throwable e) {
            String errMsg = String.format("年龄计算失败, birthday:%s", birthday);
            throw new RuntimeException(errMsg, e);
        }
    }
}
